# encoding: utf-8

import os
import urllib

from tornado import web
from tornado import wsgi
from tornado.ioloop import IOLoop
from tornado.options import options, parse_command_line, define


settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "./static/"),
    "cookie_secret": "--------------------------------------------",
    "debug": True,
}


class MaterialHandler(web.RequestHandler):
    def get(self):
        req = self.request
        url = "http://www.google.cn%s%s%s" % (
            self.request.path,
            "?" if req.query else "",
            req.query
        )
        resp = urllib.urlopen(url)
        c = resp.read()
        c = c.replace("material-design.storage.googleapis.com", "material-design.storage.ioreq.com")
        self.finish(c)


class RedirHandler(web.RequestHandler):
    def get(self, *args, **kwargs):
        req = self.request
        url = "http://www.google.cn%s%s%s" % (
            self.request.path,
            "?" if req.query else "",
            req.query
        )
        self.redirect(url)


server = web.Application(
    [
        (r"/.*", MaterialHandler),
    ], **settings
)

application = wsgi.WSGIApplication(
    [
        (r'^/.*?(jpg|png|css|js|gif)', RedirHandler),
        (r"^/.*$", MaterialHandler),
    ], **settings
)

if __name__ == '__main__':
    define("port", default=8000, help="", type=int)
    parse_command_line()
    server.listen(options.port)
    IOLoop.instance().start()